package com.jingdianjichi.subject.application.context;

import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登陆上下文对象
 */
public class LoginContextHolder {
    //    多线程问题
    //    public static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();
//    线程池多线程复用又出现问题
    public static final InheritableThreadLocal<Map<String, Object>> INHERITABLE_THREAD_LOCAL =
            new InheritableThreadLocal<>();

    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = INHERITABLE_THREAD_LOCAL.get();
        if (CollectionUtils.isEmpty(map)) {
            map = new ConcurrentHashMap<>();
        }
        return map;
    }

    public static void set(String key, Object val) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, val);
        INHERITABLE_THREAD_LOCAL.set(map);
    }

    public static Object get(String key) {
        Map<String, Object> map = getThreadLocalMap();
        return map.get(key);
    }

    public static void remove() {
        INHERITABLE_THREAD_LOCAL.remove();
    }

    public static String getLoginId() {
        Map<String, Object> map = getThreadLocalMap();
        String loginId = (String) map.get("loginId");
        return loginId;
    }

}
